package org.kymjs.kjframe.demo;

import static org.kymjs.kjframe.common.Constant.HEADER_DEVICE_KEY;
import static org.kymjs.kjframe.common.Constant.WS_BASE;

import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import org.json.JSONException;
import org.json.JSONObject;
import org.kymjs.kjframe.utils.WebsocketClient;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

public class SignalClient {

    private static final String TYPE_PARAM = "type";
    private static final String TYPE_VALUE_FEEDBACK = "feedback";
    private static final String TYPE_VALUE_SDP = "sdp";
    private static final String TYPE_VALUE_ICE = "ice";
    private static final String TYPE_VALUE_OPR = "opr"; // 远程控制操作
    private static final String TYPE_VALUE_INVITE_CODE = "infoinvitecode";

    private ScheduledExecutorService pingExecutor;



    private WebsocketClient wsClient;
    private boolean wsConnected = false;
    private WebsocketClient.WsClientInterface wsInterface;
    private String wsUrl;

    public SignalClient(String deviceId, WebsocketClient.WsClientInterface wsInterface){
        wsUrl = String.format("%s/callee/websocket?%s=%s", WS_BASE, HEADER_DEVICE_KEY,deviceId);
        this.wsInterface = wsInterface;
    }

    public Boolean start(){
        if (wsClient == null || !wsConnected) {
            initWebSocket();
            return true;
        } else {
            return false;
        }
    }

    public void stop(){
        wsClient.stop();
    }

    private void initWebSocket() {
        System.out.println(wsUrl);
        wsClient = new WebsocketClient(wsUrl, new WebSocketListener() {
            @Override
            public void onClosed(@NonNull WebSocket webSocket, int code, @NonNull String reason) {
                super.onClosed(webSocket, code, reason);
                wsConnected = false;
                System.out.println("关闭ws连接");
            }

            @Override
            public void onFailure(@NonNull WebSocket webSocket, @NonNull Throwable t, @Nullable Response response) {
                super.onFailure(webSocket, t, response);
                wsConnected = false;
                System.out.println("ws连接失败");
                System.out.println("失败原因：" + response);
            }

            @Override
            public void onOpen(@NonNull WebSocket webSocket, @NonNull Response response) {
                super.onOpen(webSocket, response);
                wsConnected = true;
                System.out.println("ws连接开启");
            }

            @Override
            public void onMessage(@NonNull WebSocket webSocket, @NonNull String text) {
                super.onMessage(webSocket, text);
                System.out.println("ws接收到了消息");
                System.out.println(text);
                handleRequest(text);
            }
        });
    }
    private void handleRequest(String message) {
        try {
            JSONObject json = new JSONObject(message);
            String type = json.getString("type");
            if (TYPE_VALUE_OPR.equals(type)) {
                // data 是字符串
                String dataStr = json.getString("data");
                wsInterface.onOprEvent(dataStr);
            } else {
                // data 是 JSONObject
                JSONObject data = json.getJSONObject("data");
                switch (type) {
                    case TYPE_VALUE_SDP:
                        wsInterface.onSdp(data);
                        break;
                    case TYPE_VALUE_ICE:
                        wsInterface.onIceCandidate(data);
                        break;
                    case TYPE_VALUE_FEEDBACK:

                        break;
                }}
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    public void send(String text){
        System.out.println("发送text"+text);
        wsClient.sendMessage(text);
    }
    }
